package com.fingard.dsp.bank.directbank.gxnx01;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/10/10.
 */
public class GXNX01Transaction extends GXNX01Base implements ITransaction {

    /**
     * 历史明细查询
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return d_7516_HisTransA(p_req7516);
    }

    /**
     * 公网-历史明细查询
     * @param p_req7516
     * @return
     * @throws Exception
     */
    public RetAtsTrans d_7516_HisTransA(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo ="";
        retAtsTrans.writeStart();
        try{
            //起始时间
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束时间
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int tmpNowReadStart = 1;//起始笔数
                int tmpNowReadNum = 0;//已查询笔数
                Map<String,Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadNum==0 || tmpNowReadNum<tmpTotalNum.get("totalCount")){
                    //签名原文
                    String signDataStr=p_req7516.actNum+"|"+convertCurToBank(p_req7516.actCur)+"|"
                            +Format.Date8Format.format(tmpCalendarFrom.getTime())+"|"
                            +Format.Date8Format.format(tmpClndrStepTo.getTime());
                    //获取签名后的数据
                    String signData=sendBankBySigned(signDataStr);
                    if("".equals(signData)) {
                        tmpRespCode = "-1";
                        tmpRespInfo = "获取签名后的数据失败，请求报文发送失败";
                        break;
                    }else {
                        XmlTextWriter xmlTextWriter = new XmlTextWriter();
                        GXNX01Header header = new GXNX01Header();
                        header.tranCode ="CBE006";
                        writeCommonHeader(xmlTextWriter,header);
                        xmlTextWriter.writeStartElement("ReqParam");
                        xmlTextWriter.writeElementString("accountNo",p_req7516.actNum);//账户
                        xmlTextWriter.writeElementString("currencyType",convertCurToBank(p_req7516.actCur));//币种
                        xmlTextWriter.writeElementString("beginDate",Format.Date8Format.format(tmpCalendarFrom.getTime()));//起始时间
                        xmlTextWriter.writeElementString("endDate",Format.Date8Format.format(tmpClndrStepTo.getTime()));//结束时间
                        xmlTextWriter.writeElementString("turnPageBgnPos",tmpNowReadStart+"");//翻页起始数据
                        xmlTextWriter.writeElementString("turnPageShowQnt",getBankConfig().getValueAsString("pageSize"));//默认每页显示数据
                        xmlTextWriter.writeElementString("branchId",bankFront.org);//机构号
                        xmlTextWriter.writeElementString("signDataStr",signDataStr.trim());//签名原文
                        xmlTextWriter.writeElementString("signData",signData.trim());//签名后数据
                        xmlTextWriter.writeEndDocument();
                        String[] bankResult = sendToBank(xmlTextWriter.toXmlString());

                        //测试
                        //String[] bankResult={"", ""};
                        //bankResult[0]="";
                        //bankResult[1]="0000||#<?xml version=\"1.0\" encoding=\"UTF-8\" ?><QLBankData><opRep><customerId>20207045881</customerId><customerNameCN>深圳保险有限公司</customerNameCN><turnPageTotalQnt>7</turnPageTotalQnt><opResult><list><row><currencyType>CNY</currencyType><loanFlag>D</loanFlag><cadDebit>14.00</cadDebit><cadCredit>0.00</cadCredit><balance>99999853.00</balance><balanceAvailable>99999853.00</balanceAvailable><oppositeAccount>172612010109607488</oppositeAccount><oppositeAccountName>刘德华股份公司</oppositeAccountName><transferDate>20180222</transferDate><remark>网银转出</remark><hostSeqNb>432160</hostSeqNb><memo>汇海转账+CC0000033W</memo></row><row><currencyType>CNY</currencyType><loanFlag>D</loanFlag><cadDebit>13.00</cadDebit><cadCredit>0.00</cadCredit><balance>99999867.00</balance><balanceAvailable>99999867.00</balanceAvailable><oppositeAccount>172612010109607488</oppositeAccount><oppositeAccountName>刘德华股份公司</oppositeAccountName><transferDate>20180222</transferDate><remark>网银转出</remark><hostSeqNb>323917</hostSeqNb><memo>汇海转账+CC0000033V</memo></row><row><currencyType>CNY</currencyType><loanFlag>C</loanFlag><cadDebit>0.00</cadDebit><cadCredit>90000000.00</cadCredit><balance>99999880.00</balance><balanceAvailable>99999880.00</balanceAvailable><oppositeAccount/><oppositeAccountName/><transferDate>20180222</transferDate><remark>柜面存入</remark><hostSeqNb>252177</hostSeqNb><memo>发发  发发</memo></row><row><currencyType>CNY</currencyType><loanFlag>D</loanFlag><cadDebit>10.00</cadDebit><cadCredit>0.00</cadCredit><balance>9999880.00</balance><balanceAvailable>9999880.00</balanceAvailable><oppositeAccount>6235881082314405190</oppositeAccount><oppositeAccountName>计博玉</oppositeAccountName><transferDate>20180222</transferDate><remark>网银跨行快汇转出</remark><hostSeqNb>252078</hostSeqNb><memo>网银跨行</memo></row><row><currencyType>CNY</currencyType><loanFlag>D</loanFlag><cadDebit>-10.00</cadDebit><cadCredit>0.00</cadCredit><balance>9999890.00</balance><balanceAvailable>9999890.00</balanceAvailable><oppositeAccount>6214520000000068</oppositeAccount><oppositeAccountName/><transferDate>20180222</transferDate><remark>网银取消</remark><hostSeqNb>251963</hostSeqNb><memo>取款冲销</memo></row><row><currencyType>CNY</currencyType><loanFlag>D</loanFlag><cadDebit>10.00</cadDebit><cadCredit>0.00</cadCredit><balance>9999880.00</balance><balanceAvailable>9999880.00</balanceAvailable><oppositeAccount>6214520000000068</oppositeAccount><oppositeAccountName>朱明宏</oppositeAccountName><transferDate>20180222</transferDate><remark>网银跨行快汇转出</remark><hostSeqNb>251953</hostSeqNb><memo>网银跨行</memo></row><row><currencyType>CNY</currencyType><loanFlag>D</loanFlag><cadDebit>10.00</cadDebit><cadCredit>0.00</cadCredit><balance>9999890.00</balance><balanceAvailable>9999890.00</balanceAvailable><oppositeAccount>172612010109607488</oppositeAccount><oppositeAccountName>刘德华股份公司</oppositeAccountName><transferDate>20180222</transferDate><remark>网银转出</remark><hostSeqNb>251871</hostSeqNb><memo>运费</memo></row></list></opResult></opRep></QLBankData>\n";
                        //WriteBankLogStep2(bankResult[1]);

                        if(bankResult[0].length()==0){
                            String[] result=bankResult[1].split("\\|");
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(result[2].substring(1),tmpSbMsg);
                            if(tmpBkReader!=null){
                                String rspCode = result[0];
                                String rspMsg = result[1];
                                if (isActiveRetCode(rspCode)) {
                                    //符合条件的条数，总明细数
                                    String totalCount = tmpBkReader.getFirstText("/QLBankData/opRep/turnPageTotalQnt");
                                    if(tmpTotalNum.containsKey("totalCount")){
                                        if(!tmpTotalNum.get("totalCount").equals(Integer.valueOf(totalCount))){
                                            tmpRespCode ="-1";
                                            tmpRespInfo = "相同条件前后查出来的总数不一致";
                                            break;
                                        }
                                    }else{
                                        if("0".equals(totalCount)){
                                            tmpRespCode ="0";
                                            tmpRespInfo = "该时间段的总明细条数为0";
                                            break;
                                        }
                                        tmpTotalNum.put("totalCount",Integer.valueOf(totalCount));//记录总条数
                                    }
                                    int readCount =0;
                                    while (tmpBkReader.read("/QLBankData/opRep/opResult/list/row")){
                                        XElement readXElement = tmpBkReader.readedXElement;
                                        RetAtsTransDetail detail = new RetAtsTransDetail();
                                        detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("currencyType"));
                                        String cdFlag = readXElement.getSingleTextNotNull("loanFlag").trim();//借贷标志 01借02贷
                                        if (cdFlag.equals("D")) {
                                            detail.tranAmt=readXElement.getSingleTextNotNull("cadDebit").trim();//交易金额
                                            if(detail.tranAmt.indexOf("-")>=0) {
                                                detail.cdFlag = "2";
                                                detail.tranAmt = detail.tranAmt.substring(1);
                                            }else{
                                                detail.cdFlag = "1";
                                            }
                                        } else if(cdFlag.equals("C")) {
                                            detail.tranAmt=readXElement.getSingleTextNotNull("cadCredit").trim();//交易金额
                                            if(detail.tranAmt.indexOf("-")>=0){
                                                detail.cdFlag = "1";
                                                detail.tranAmt = detail.tranAmt.substring(1);
                                            }else{
                                                detail.cdFlag = "2";
                                            }
                                        }else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志( " + cdFlag + ")无法识别，请与银行核对";
                                            break;
                                        }
                                        detail.accBal = readXElement.getSingleTextNotNull("balance");//余额
                                        detail.recAccNum = readXElement.getSingleTextNotNull("oppositeAccount");//对方账户
                                        detail.recAccName = readXElement.getSingleTextNotNull("oppositeAccountName");//对方账户名
                                        detail.usage = readXElement.getSingleTextNotNull("memo");//备注
                                        detail.abstr = pickupAbstr(detail.usage);//对账码
                                        detail.tranDate=DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("transferDate"));//交易日期
                                        detail.valueDate = detail.tranDate;//起息日
                                        detail.tranTime=detail.tranDate+" 00:00:00";//交易时间
                                        detail.askNumber=readXElement.getSingleTextNotNull("hostSeqNb");//核心流水号
                                        retAtsTrans.writeRetDetail(detail);
                                        readCount++;
                                    }
                                    tmpNowReadNum +=readCount;//已查询条数
                                    if(Integer.parseInt(totalCount)>tmpNowReadNum){
                                        //总条数大于已查询条数，说明查询了默认条数的明细
                                        if(readCount!=Integer.valueOf(getBankConfig().getValueAsString("pageSize"))){
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "统计明细有误";
                                            break;
                                        }
                                    }
                                    if(Integer.parseInt(totalCount)<tmpNowReadNum){
                                        //总条数小于已查询条数,说明数据异常
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "统计明细有误";
                                        break;
                                    }
                                    tmpNowReadStart +=readCount;//下一次起始位置=起始位置+循环次数
                                }else{
                                    tmpRespCode = "-1";
                                    tmpRespInfo = rspMsg;
                                    break;
                                }
                            }else{
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpSbMsg.toString();
                                break;
                            }
                        }else{
                            tmpRespCode = "-1";
                            tmpRespInfo = bankResult[1];
                            break;
                        }
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细查询
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return d_7515_TodayTransA(p_req7515);
    }

    /**
     * 公网-今日明细查询
     * @param p_req7515
     * @return
     * @throws Exception
     */
    public RetAtsTrans d_7515_TodayTransA(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
